import createVanilla from 'zustand/vanilla'
import { subscribeWithSelector } from 'zustand/middleware'
import create from 'zustand'
import { isCascadeTree } from '../../main/table/all/utils'
import { isMatch } from '@/pages/manager/utils/utils'
import { IMcc } from '@/api/manager/type'
import { MccModel } from '../../main/table/all/translator'
import { Meeting } from '@/api/manager/meeting'
import { Mt } from '@/api/manager/mt'

export interface ItemData {
	mcc: IMcc
	nestingLevel: number
	mtKey: string
}
interface IL {
	mcc: Mt
	mtKey: string
}
type StateStore = {
	openMap: { [mtKey: string]: boolean }
	list: ItemData[]
}
type IStore = StateStore & {
	update: (d: Partial<StateStore>) => void
	reset: () => void
	getListFromTableAll: (tree: MccModel<Meeting>, keywords: string) => void
	getListFromTable: <T extends IL>(list: T[], keywords: string) => void
}
const initialState: StateStore = {
	openMap: {},
	list: [],
}
export const store = createVanilla<IStore>()(
	subscribeWithSelector((set, get) => ({
		...initialState,
		update: (d) => set({ ...d }),
		reset: () => set(initialState),
		getListFromTableAll: (tree, keywords) => {
			const isCascade = isCascadeTree(tree)
			let result = []
			if (isCascade) {
				let stack: MccModel<IMcc>[] = [tree]
				let newOpenMap: { [mtKey: string]: boolean } = {}
				const openMap = get().openMap
				while (stack.length !== 0) {
					const item = stack.shift()!
					let isMatchSearch = true
					//在线会议始终满足search
					if (item.mcc.isMt) {
						//终端
						isMatchSearch = isMatch(item.mcc, keywords)
					} else if (!item.mcc.status.isOnline) {
						//离线会议
						isMatchSearch = isMatch(item.mcc, keywords)
					}
					if (isMatchSearch) {
						result.push({
							mcc: item.mcc,
							nestingLevel: item.nestingLevel,
							mtKey: item.mtKey,
						})
						if (!item.mcc.isMt && item.mcc.status.isOnline) {
							if (
								(item.mtKey === '0.0.0.0_0' || item.mcc.id === '0_1') &&
								openMap[item.mtKey] === undefined
							) {
								//初始化默认展开本级和上级
								openMap[item.mtKey] = true
							}
							newOpenMap[item.mtKey] = openMap[item.mtKey] !== undefined ? openMap[item.mtKey] : false
							if (newOpenMap[item.mtKey]) {
								for (let i = item.children.length - 1; i >= 0; i--) {
									stack.unshift({
										mcc: item.children[i].mcc,
										mtKey: item.children[i].mtKey,
										nestingLevel: item.nestingLevel + 1,
										children: item.children[i].children,
									} as MccModel<IMcc>)
								}
							}
						}
					}
				}
				/**
				 * 由于推送消息都是单条单条处理，所以 tree 的更新存在先后性
				 * 离线会议和被删除的会议需要进行判断，从openMap内移除。否则再次上线可能会默认展开，导致其下级终端并没有出现
				 */
				set({ openMap: newOpenMap })
			} else {
				let stack = tree.children
				for (let i = 0; i < stack.length; i++) {
					const item = stack[i]
					let isMatchSearch = isMatch(item.mcc, keywords)
					if (isMatchSearch) {
						result.push({
							mcc: item.mcc,
							nestingLevel: 0,
							children: [],
							mtKey: item.mtKey,
						})
					}
				}
			}
			set({ list: result })
		},
		getListFromTable(list, keywords) {
			let result = []
			for (let i = 0; i < list.length; i++) {
				const item = list[i]
				let isMatchSearch = isMatch(item.mcc, keywords)
				if (isMatchSearch) {
					result.push({
						mcc: item.mcc,
						nestingLevel: 0,
						children: [],
						mtKey: item.mtKey,
					})
				}
			}
			set({ list: result })
		},
	}))
)
export const useMemberListStore = create(store)
